<template>
  <div class="zset-operations">
    <el-card class="operation-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span><el-icon><Plus /></el-icon> 添加有序集合元素</span>
        </div>
      </template>
      <el-form :model="zaddForm" label-width="120px" label-position="left">
        <el-form-item label="键名">
          <el-input v-model="zaddForm.key" placeholder="请输入键名" clearable />
        </el-form-item>
        <el-form-item label="分数">
          <el-input-number v-model="zaddForm.score" :precision="1" :step="0.1" />
        </el-form-item>
        <el-form-item label="值">
          <el-input v-model="zaddForm.value" placeholder="请输入值" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleZAdd" :icon="Plus">添加</el-button>
          <el-button @click="resetAddForm" :icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="operation-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span><el-icon><Search /></el-icon> 按索引范围获取</span>
        </div>
      </template>
      <el-form :model="zrangeForm" label-width="120px" label-position="left">
        <el-form-item label="键名">
          <el-input v-model="zrangeForm.key" placeholder="请输入键名" clearable />
        </el-form-item>
        <el-form-item label="起始索引">
          <el-input-number v-model="zrangeForm.start" :min="0" :step="1" />
        </el-form-item>
        <el-form-item label="结束索引">
          <el-input-number v-model="zrangeForm.end" :min="-1" :step="1" />
          <div class="form-tip">提示: -1表示最后一个元素</div>
        </el-form-item>
        <el-form-item label="显示分数">
          <el-switch v-model="zrangeForm.withScores" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleZRange" :icon="Sort">正序获取</el-button>
          <el-button type="success" @click="handleZRevRange" :icon="Sort">倒序获取</el-button>
          <el-button @click="resetRangeForm" :icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>
      <div v-if="zrangeResult.length > 0 || zrangeResultEmpty" class="result-box">
        <div class="result-header">
          <h4>结果:</h4>
          <el-button type="text" @click="copyRangeResult" :icon="CopyDocument">复制</el-button>
        </div>
        <el-alert
          v-if="zrangeResult.length === 0 && zrangeResultEmpty"
          title="有序集合为空或不存在"
          type="warning"
          :closable="false"
          show-icon
        />
        <el-table 
          v-else 
          :data="zrangeResultArray" 
          stripe 
          border 
          style="width: 100%"
          max-height="300"
        >
          <el-table-column prop="index" label="索引" width="80" />
          <el-table-column prop="value" label="值" />
          <el-table-column v-if="zrangeForm.withScores" prop="score" label="分数" width="100" />
        </el-table>
      </div>
    </el-card>

    <el-card class="operation-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span><el-icon><Search /></el-icon> 按分数范围获取</span>
        </div>
      </template>
      <el-form :model="zrangebyscoreForm" label-width="120px" label-position="left">
        <el-form-item label="键名">
          <el-input v-model="zrangebyscoreForm.key" placeholder="请输入键名" clearable />
        </el-form-item>
        <el-form-item label="最小分数">
          <el-input-number v-model="zrangebyscoreForm.min" :precision="1" :step="0.1" />
        </el-form-item>
        <el-form-item label="最大分数">
          <el-input-number v-model="zrangebyscoreForm.max" :precision="1" :step="0.1" />
        </el-form-item>
        <el-form-item label="显示分数">
          <el-switch v-model="zrangebyscoreForm.withScores" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleZRangeByScore" :icon="Sort">正序获取</el-button>
          <el-button type="success" @click="handleZRevRangeByScore" :icon="Sort">倒序获取</el-button>
          <el-button @click="resetRangeByScoreForm" :icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>
      <div v-if="zrangebyscoreResult.length > 0 || zrangebyscoreResultEmpty" class="result-box">
        <div class="result-header">
          <h4>结果:</h4>
          <el-button type="text" @click="copyRangeByScoreResult" :icon="CopyDocument">复制</el-button>
        </div>
        <el-alert
          v-if="zrangebyscoreResult.length === 0 && zrangebyscoreResultEmpty"
          title="有序集合为空或不存在，或没有符合分数范围的元素"
          type="warning"
          :closable="false"
          show-icon
        />
        <el-table 
          v-else 
          :data="zrangebyscoreResultArray" 
          stripe 
          border 
          style="width: 100%"
          max-height="300"
        >
          <el-table-column prop="index" label="索引" width="80" />
          <el-table-column prop="value" label="值" />
          <el-table-column v-if="zrangebyscoreForm.withScores" prop="score" label="分数" width="100" />
        </el-table>
      </div>
    </el-card>

    <el-card class="operation-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span><el-icon><Remove /></el-icon> 移除有序集合元素</span>
        </div>
      </template>
      <el-form :model="zremForm" label-width="120px" label-position="left">
        <el-form-item label="键名">
          <el-input v-model="zremForm.key" placeholder="请输入键名" clearable />
        </el-form-item>
        <el-form-item label="值">
          <el-input v-model="zremForm.value" placeholder="请输入值" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="warning" @click="handleZRem" :icon="Remove">移除</el-button>
          <el-button @click="resetRemForm" :icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="operation-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span><el-icon><Delete /></el-icon> 删除有序集合</span>
        </div>
      </template>
      <el-form :model="deleteForm" label-width="120px" label-position="left">
        <el-form-item label="键名">
          <el-input v-model="deleteForm.key" placeholder="请输入键名" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="danger" @click="handleDelete" :icon="Delete">删除</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus, Remove, Search, Refresh, Delete, Sort, CopyDocument } from '@element-plus/icons-vue'
import { zAdd, zRange, zRevRange, zRangeByScore, zRevRangeByScore, zRem, del } from '../api/redis'

// 确保图标组件被正确导入和注册

const zaddForm = reactive({
  key: '',
  score: 1.0,
  value: ''
})

const zrangeForm = reactive({
  key: '',
  start: 0,
  end: -1,
  withScores: true
})

const zrangebyscoreForm = reactive({
  key: '',
  min: 0,
  max: 100,
  withScores: true
})

const zremForm = reactive({
  key: '',
  value: ''
})

const deleteForm = reactive({
  key: ''
})

const zrangeResult = ref<any[]>([])
const zrangeResultEmpty = ref(false)
const zrangebyscoreResult = ref<any[]>([])
const zrangebyscoreResultEmpty = ref(false)

// 将范围结果转换为表格数据
const zrangeResultArray = computed(() => {
  if (!zrangeForm.withScores) {
    return zrangeResult.value.map((value, index) => ({
      index: zrangeForm.start + index,
      value
    }))
  } else {
    const result = []
    for (let i = 0; i < zrangeResult.value.length; i += 2) {
      result.push({
        index: zrangeForm.start + i / 2,
        value: zrangeResult.value[i],
        score: zrangeResult.value[i + 1]
      })
    }
    return result
  }
})

// 将分数范围结果转换为表格数据
const zrangebyscoreResultArray = computed(() => {
  if (!zrangebyscoreForm.withScores) {
    return zrangebyscoreResult.value.map((value, index) => ({
      index,
      value
    }))
  } else {
    const result = []
    for (let i = 0; i < zrangebyscoreResult.value.length; i += 2) {
      result.push({
        index: i / 2,
        value: zrangebyscoreResult.value[i],
        score: zrangebyscoreResult.value[i + 1]
      })
    }
    return result
  }
})

const handleZAdd = async () => {
  if (!zaddForm.key || !zaddForm.value) {
    ElMessage.warning('请输入键名和值')
    return
  }
  
  try {
    await zAdd(zaddForm.key, zaddForm.score, zaddForm.value)
    ElMessage.success('添加成功')
    resetAddForm()
  } catch (error) {
    ElMessage.error('添加失败')
  }
}

const handleZRange = async () => {
  if (!zrangeForm.key) {
    ElMessage.warning('请输入键名')
    return
  }
  
  try {
    const response = await zRange(zrangeForm.key, zrangeForm.start, zrangeForm.end, zrangeForm.withScores)
    const members = response.data?.members || []
    zrangeResult.value = Array.isArray(members) ? members : Array.from(members)
    zrangeResultEmpty.value = true
    
    if (zrangeResult.value.length === 0) {
      ElMessage.warning('有序集合为空或不存在')
    } else {
      ElMessage.success('获取成功')
    }
  } catch (error) {
    ElMessage.error('获取失败')
    zrangeResult.value = []
    zrangeResultEmpty.value = false
  }
}

const handleZRevRange = async () => {
  if (!zrangeForm.key) {
    ElMessage.warning('请输入键名')
    return
  }
  
  try {
    const response = await zRevRange(zrangeForm.key, zrangeForm.start, zrangeForm.end, zrangeForm.withScores)
    const members = response.data?.members || []
    zrangeResult.value = Array.isArray(members) ? members : Array.from(members)
    zrangeResultEmpty.value = true
    
    if (zrangeResult.value.length === 0) {
      ElMessage.warning('有序集合为空或不存在')
    } else {
      ElMessage.success('获取成功')
    }
  } catch (error) {
    ElMessage.error('获取失败')
    zrangeResult.value = []
    zrangeResultEmpty.value = false
  }
}

const handleZRangeByScore = async () => {
  if (!zrangebyscoreForm.key) {
    ElMessage.warning('请输入键名')
    return
  }
  
  try {
    const response = await zRangeByScore(zrangebyscoreForm.key, zrangebyscoreForm.min, zrangebyscoreForm.max, zrangebyscoreForm.withScores)
    const members = response.data?.members || []
    zrangebyscoreResult.value = Array.isArray(members) ? members : Array.from(members)
    zrangebyscoreResultEmpty.value = true
    
    if (zrangebyscoreResult.value.length === 0) {
      ElMessage.warning('有序集合为空或不存在，或没有符合分数范围的元素')
    } else {
      ElMessage.success('获取成功')
    }
  } catch (error) {
    ElMessage.error('获取失败')
    zrangebyscoreResult.value = []
    zrangebyscoreResultEmpty.value = false
  }
}

const handleZRevRangeByScore = async () => {
  if (!zrangebyscoreForm.key) {
    ElMessage.warning('请输入键名')
    return
  }
  
  try {
    const response = await zRevRangeByScore(zrangebyscoreForm.key, zrangebyscoreForm.max, zrangebyscoreForm.min, zrangebyscoreForm.withScores)
    const members = response.data?.members || []
    zrangebyscoreResult.value = Array.isArray(members) ? members : Array.from(members)
    zrangebyscoreResultEmpty.value = true
    
    if (zrangebyscoreResult.value.length === 0) {
      ElMessage.warning('有序集合为空或不存在，或没有符合分数范围的元素')
    } else {
      ElMessage.success('获取成功')
    }
  } catch (error) {
    ElMessage.error('获取失败')
    zrangebyscoreResult.value = []
    zrangebyscoreResultEmpty.value = false
  }
}

const handleZRem = async () => {
  if (!zremForm.key || !zremForm.value) {
    ElMessage.warning('请输入键名和值')
    return
  }
  
  try {
    await zRem(zremForm.key, zremForm.value)
    ElMessage.success('移除成功')
    resetRemForm()
    
    // 如果当前正在查询的键被修改，更新结果
    if (zrangeForm.key === zremForm.key) {
      handleZRange()
    }
    if (zrangebyscoreForm.key === zremForm.key) {
      handleZRangeByScore()
    }
  } catch (error) {
    ElMessage.error('移除失败')
  }
}

const handleDelete = async () => {
  if (!deleteForm.key) {
    ElMessage.warning('请输入键名')
    return
  }
  
  try {
    await del(deleteForm.key)
    ElMessage.success('删除成功')
    deleteForm.key = ''
    
    // 如果当前正在查询的键被删除，清空结果
    if (zrangeForm.key === deleteForm.key) {
      zrangeResult.value = []
      zrangeResultEmpty.value = false
    }
    if (zrangebyscoreForm.key === deleteForm.key) {
      zrangebyscoreResult.value = []
      zrangebyscoreResultEmpty.value = false
    }
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

const resetAddForm = () => {
  zaddForm.key = ''
  zaddForm.score = 1.0
  zaddForm.value = ''
}

const resetRangeForm = () => {
  zrangeForm.key = ''
  zrangeForm.start = 0
  zrangeForm.end = -1
  zrangeResult.value = []
  zrangeResultEmpty.value = false
}

const resetRangeByScoreForm = () => {
  zrangebyscoreForm.key = ''
  zrangebyscoreForm.min = 0
  zrangebyscoreForm.max = 100
  zrangebyscoreResult.value = []
  zrangebyscoreResultEmpty.value = false
}

const resetRemForm = () => {
  zremForm.key = ''
  zremForm.value = ''
}

const copyRangeResult = () => {
  if (zrangeResult.value.length > 0) {
    navigator.clipboard.writeText(JSON.stringify(zrangeResult.value, null, 2))
    ElMessage.success('已复制到剪贴板')
  }
}

const copyRangeByScoreResult = () => {
  if (zrangebyscoreResult.value.length > 0) {
    navigator.clipboard.writeText(JSON.stringify(zrangebyscoreResult.value, null, 2))
    ElMessage.success('已复制到剪贴板')
  }
}
</script>

<style scoped>
.zset-operations {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
  gap: 20px;
}

.operation-card {
  margin-bottom: 20px;
  transition: all 0.3s;
}

.operation-card:hover {
  transform: translateY(-5px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
}

.card-header .el-icon {
  margin-right: 5px;
}

.result-box {
  margin-top: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 4px;
  border-left: 4px solid #409EFF;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.result-header h4 {
  margin: 0;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .zset-operations {
    grid-template-columns: 1fr;
  }
}
</style>